package com.jsgt.greekfire.ui.home.genesisblock


import android.R.id.edit
import android.annotation.SuppressLint
import android.app.Dialog
import android.os.Handler
import android.text.Editable
import android.text.InputFilter
import android.text.TextUtils
import android.text.TextWatcher
import android.util.Log
import android.view.View
import android.widget.EditText
import android.widget.TextView
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProvider
import com.fhx.core.base.BaseActivity
import com.fhx.core.utils.DialogUtil
import com.fhx.core.utils.PriceFormatUtil
import com.fhx.core.utils.ToastUtils
import com.jsgt.greekfire.R
import com.jsgt.greekfire.bean.BlockStatus
import com.jsgt.greekfire.common.util.NetDataManager
import com.jsgt.greekfire.event.AssetsEvent
import com.jsgt.greekfire.factory.CoinViewModelFactory
import com.jsgt.greekfire.factory.UserViewModelFactory
import com.jsgt.greekfire.viewmodel.CoinViewModel
import com.jsgt.greekfire.viewmodel.UserViewModel
import kotlinx.android.synthetic.main.activity_genesis_block.*
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode
import java.math.BigDecimal
import java.text.DecimalFormat


class GenesisBlockActivity : BaseActivity(), View.OnClickListener {

    override fun getLayoutId(): Int = R.layout.activity_genesis_block

    private val userViewModel: UserViewModel by lazy {
        ViewModelProvider(
            this,
            UserViewModelFactory()
        ).get(UserViewModel::class.java)
    }

    private val coinViewModel: CoinViewModel by lazy {
        ViewModelProvider(
            this,
            CoinViewModelFactory()
        ).get(CoinViewModel::class.java)
    }

    private var blockStatus: BlockStatus? = null

    private var pwdDialog1: Dialog? = null

    var df2: DecimalFormat = DecimalFormat("#.00")
    private var usdt_balance = 0.0//可用usdt余额
    private var hasBuy=false;//是否购买了
    @SuppressLint("SetTextI18n")
    override fun main() {
        super.main()
        title = "创世区块"
//        setRightImage(R.mipmap.icon_refresh).setOnClickListener {
//            refresh()
//        }

        exit_tv.setOnClickListener(this)

        //创世区块配置中的状态
        coinViewModel.checkGenesisBlockStatus()

        //获取资产
        NetDataManager.getUserAssets()
        coinViewModel.checkGenesisBlockStatusLiveData.observe(this, Observer {

            blockStatus = it

            block_text1.text = it.ruleTitle.toString()
            block_text2.text = it.ruleDetail.toString()


            when (it.activeStatus) {
                0 -> {
                    exit_tv.text = "活动未开始"
                    exit_tv.background = resources.getDrawable(R.drawable.bg_security_set3)
                }
                1 -> {

                    when (it.userStatus) {
                        //未参与
                        0 -> {
                            exit_tv.background = resources.getDrawable(R.drawable.bg_security_set2)
//                            exit_tv.isClickable = true

                            Log.e("TAG", "main: " + "222222222222222222")
                        }
                        //已参与
                        1 -> {
                            exit_tv.text = "活动已参与"
                            exit_tv.background = resources.getDrawable(R.drawable.bg_security_set3)
//                            exit_tv.isClickable = false
                            Log.e("TAG", "main: " + "1111111111111111")
                        }
                    }
                }
            }


            showProgress(false)

        })


        coinViewModel.checkGenesisBlockparticipateLiveData.observe(this, Observer {
            showProgress(false)
            showToast(it.toString())
            pwdDialog1?.dismiss()
            finish()

        })
        coinViewModel.errorLiveData.observe(this, Observer {
            showProgress(false)
        })

    }
    override fun onDestroy() {
        super.onDestroy()

    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onAssetsEvent(e: AssetsEvent) {
        for (bean in NetDataManager.assetsList) {
            if (TextUtils.equals("2", bean.assetGuid)) {
                usdt_balance = bean.assetBalance!!
                break
            }
        }
    }


    @SuppressLint("SetTextI18n")
    fun popwindos() {

        val contentView = layoutInflater.inflate(R.layout.dialog_genesisblock_pop, null, false)
        pwdDialog1 = DialogUtil.show(this, contentView)
        pwdDialog1?.setOnDismissListener {
            pwdDialog1 = null
        }
        pwdDialog1?.setCancelable(true)
        pwdDialog1?.setCanceledOnTouchOutside(true)
        pwdDialog1?.show()

        val GenesisBlock_pwd = contentView.findViewById<EditText>(R.id.GenesisBlock_pwd)

        val GenesisBlock_price = contentView.findViewById<TextView>(R.id.GenesisBlock_price)
        val GenesisBlock_money = contentView.findViewById<TextView>(R.id.GenesisBlock_money)

        val GenesisBlock_number = contentView.findViewById<EditText>(R.id.GenesisBlock_number)
        contentView.findViewById<EditText>(R.id.GenesisBlock_number)
            .addTextChangedListener(object : TextWatcher {
                override fun afterTextChanged(s: Editable?) {

                    //判断内容是否为""
                    if (s.toString() == "") {
                        //如果是则直接让成员变量putNumber为0
                        GenesisBlock_money.text = "0U"
                    } else {
                            //如果不是则将字符串类型转换成Double类型并赋给pubNumber
                            GenesisBlock_money.text =
                                "" + df2.format(
                                    BigDecimal(blockStatus!!.gfcPrice).multiply(
                                        BigDecimal(
                                            GenesisBlock_number.text.toString().trim()
                                        )
                                    )
                                ).toString() + "U"
                        }


                }

                override fun beforeTextChanged(
                    s: CharSequence?,
                    start: Int,
                    count: Int,
                    after: Int
                ) {

                }

                override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {

                }

            })




        GenesisBlock_price.text = "" + blockStatus!!.gfcPrice.toString() + "U"




        contentView.findViewById<TextView>(R.id.pop_sure).setOnClickListener {

            if (TextUtils.isEmpty(GenesisBlock_number.text.toString().trim())) {
                showToast(getString(R.string.Please_input))
                return@setOnClickListener
            }


            //抢购数量必须大于100且必须是100的整数倍
            if (GenesisBlock_number.text.toString().trim().toInt() in 1001..99) {
                showToast(getString(R.string.Please_input))
                return@setOnClickListener
            }

            if((GenesisBlock_number.text.toString().trim().toInt()%100)>0){
                showToast("抢购数量必须大于100且必须是100的整数倍")
                return@setOnClickListener
            }
            if(GenesisBlock_number.text.toString().trim().toInt()>1000){
                showToast("抢购数量不能大于1000")
                return@setOnClickListener
            }
            if (TextUtils.isEmpty(GenesisBlock_pwd.text.toString().trim())) {
                showToast(getString(R.string.please_password))
                return@setOnClickListener
            }


            //余额获取
            usdt_balance = PriceFormatUtil.format(usdt_balance, 2).toDouble()

            NetDataManager.getUserAssets()

//                coinViewModel.coinTypeList()
            coinViewModel.checkGenesisBlockparticipate(
                GenesisBlock_number.text.toString().trim().toDouble(),
                blockStatus!!.ingGuid,
                GenesisBlock_pwd.text.toString().trim()
            )

            pwdDialog1?.dismiss()
            showProgress(false)


        }


    }


    override fun onClick(v: View?) {
        when (v?.id) {
            R.id.exit_tv -> {
                when(blockStatus?.activeStatus){
                    0->{
                        ToastUtils.show("活动未开始")
                    }
                    1->{
                        when(blockStatus?.userStatus){
                            0->{
                                popwindos()
                            }
                            1->{
                                ToastUtils.show("你已参与本期活动")
                            }
                        }
                    }
                }

            }
        }
    }

}


